package com.kurumi.autoprint.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;


public class FileUtil {
	private static Logger log = LoggerFactory.getLogger(FileUtil.class);

	public static boolean createOrEditFile(String data,String fileDir,String fileName) throws IOException{
		File destFile = new File(fileDir,fileName);
		if(!destFile.exists()){
			File destDir = new File(fileDir);
			if(!destDir.exists()){
				destDir.mkdirs();
			}
			destFile.createNewFile();
		}
		
		FileOutputStream fileOutputStream=new FileOutputStream(destFile);  
        OutputStreamWriter outputWriter=new OutputStreamWriter(fileOutputStream,"UTF-8");  
        outputWriter.write(data);
         
        outputWriter.close();  
        fileOutputStream.close();  

       
		return true;
	}
	
	public static Map<String, Object> readLineFile(String filePath, String fileName) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();

		try {
			File destFile = new File(filePath, fileName);
			String jsonStr = null;
			if (destFile.exists()) {
				// FileReader fr = new FileReader(destFile);
				BufferedReader br = new BufferedReader(
						new InputStreamReader(new FileInputStream(filePath + fileName), "UTF-8"));
				jsonStr = br.readLine();
				jsonMap = JsonUtil.jsonToPojo(jsonStr, Map.class);

			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		return jsonMap;
	}
	
	/**
	 * 判断文件是否存在
	 * @param filePath
	 * @return
	 */
	public  static boolean fileIsExists(String filePath) {
		return  new File(filePath).exists()?true:false;
	}
	
	
	//删除文件
		public static void deleteDirectory(File dirFile) {
			// 如果文件或文件夹不存在，则直接返回
			if (!dirFile.exists() && !dirFile.isDirectory()) {
				return;
			}

			File[] files = dirFile.listFiles();
			// 遍历删除文件夹中的文件
			for (int i = 0; i < files.length; i++) {
				if (files[i].isFile()) {
					deleteFile(files[i].getAbsolutePath());

				} else {
					deleteDirectory(files[i].getAbsolutePath());

				}
			}

		}

		// 删除文件
		public static void deleteFile(String filePath) {
			File file = new File(filePath);
			if (file.isDirectory()) {
				deleteDirectory(filePath);
			}
			if (file.isFile() && file.exists()) {
				file.delete();
			}

		}

		// 删除目录及目录下的文件
		public static void deleteDirectory(String filePath) {
			// 如果spath不以文件分隔结尾，自动添加文件分隔符
			if (!filePath.endsWith(File.separator)) {
				filePath = filePath + File.separator;
			}
	        deleteDirectory(new File(filePath));
		}

		
		/**
		 * 删除不是今天创建的文件
		 */
		public static synchronized void deleteNotTodayCreateFile(String rootDir) {
			File fileDir = new File(rootDir);
			
			if (!fileDir.isDirectory()) {
				log.error("rootDir={}, 不是一个目录, 无法删除该目录下面不是今天生成的文件!");
				return;
			}
			
			File[] files = fileDir.listFiles();
			String currentDateFormat = DateUtil.dateFormat(DateUtil.DATE_FORMATE, new Date());
			
			if (null != files && files.length > 0) {
				for (File file : files) {
					if (file.isDirectory() && !file.getName().trim().equalsIgnoreCase(currentDateFormat)) {
						try {
							deleteDirectory(file.getAbsolutePath());
							file.delete();
						} catch (Exception e) {
							log.error("删除文件异常, fileName={}, exceptionMsg={}", 
									file.getAbsolutePath(), ExceptionUtil.getStackTrace(e));
						}
					}
				}
			}
			
			System.out.println(files.length);
		}

		public static String readResourceFile(String fileName) {
			String str = "";
			InputStream inputStream = null;
			BufferedReader br = null;
			
			try {
				File file = ResourceUtils.getFile("classpath:" + fileName.trim());
				inputStream = new FileInputStream(file);
				
				StringBuilder sb = new StringBuilder();
				String line;
				br = new BufferedReader(new InputStreamReader(inputStream));
				
				while ((line = br.readLine()) != null) {
					sb.append(line);
				}
				
				str = sb.toString();
			} catch (Exception e) {
				log.error("读取springboot,resource下的资源文件fileName={}异常, exceptionMsg={}", fileName, ExceptionUtil.getStackTrace(e));
			} finally {
				if (null != br) {
					try {
						br.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				
				if (null != inputStream) {
					try {
						inputStream.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			
			return str;
		}
		
	    /**
	     * the traditional io way
	     *
	     * @param filename
	     * @return
	     * @throws IOException
	     */
	    public static byte[] toByteArray(String filename) throws IOException {
	 
	        File f = new File(filename);
	        if (!f.exists()) {
	            throw new FileNotFoundException(filename);
	        }
	 
	        ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
	        BufferedInputStream in = null;
	        
	        try {
	            in = new BufferedInputStream(new FileInputStream(f));
	            int buf_size = 1024;
	            byte[] buffer = new byte[buf_size];
	            int len = 0;
	            
	            while (-1 != (len = in.read(buffer, 0, buf_size))) {
	                bos.write(buffer, 0, len);
	            }
	            
	            return bos.toByteArray();
	        } catch (IOException e) {
	            e.printStackTrace();
	            throw e;
	        } finally {
	            try {
	                in.close();
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	            bos.close();
	        }
	    }
		
		
		
		
		
		
	
}









